<template>
  <view class="page index-page rec-bag-pop-page">
    <uni-navbar
      title="签到福利"
      :border="false"
      :fixed="true"
      :height="barHeight"
      :rightWidth="60"
      :leftWidth="60"
      titleStyle="color:#fff;fontSize:18px;"
      :bgColor="isWhiteAppBar ? '#FF5500' : 'transparent'"
      :placeholder="false"
      :autoBack="true"
    >
      <view slot="left">
        <image v-if="!isMpAlipay && !isMpBaidu && !isMpToutiao" src="../../static/images/back_white2.png" class="back-icon" style="margin-left: -10rpx;"></image>
      </view>
    </uni-navbar>

    <scroll-view
      class="box-1"
      :scroll-y="true"
      :refresher-enabled="false"
      :style="{paddingTop: headHt}"
      refresher-background="#ffffff"
      @scroll="scrollEv"
    >

      <view class="text-center font16 font-semibold" style="color:#fff;" @tap="toCoinDetails">
        今日赚取<text style="font-size:56rpx;font-weight:600;margin:0 4rpx;">{{ signGroupitem.golds }}</text>金币
      </view>
      <view class="sign-center">
        <view class="center-box">
          <view class="flex justify-between items-center">
            <text class="font16 font-b">签到任务</text>
            <view class="flex items-center font-semibold" v-if="isViewNextBtn" @tap ="changTask">
              <image :src="staticHost+'/refresh_1.png'" mode="widthFix" style="width:36rpx;margin-right:12rpx;"></image>
              换一个
            </view>
          </view>

          <view class="font16 font-b text-center" style="margin-top:40rpx;">
            {{ currentTask.name }}
            <text v-if="currentTask.taskType == 3">
              （{{currentTask.cmpCount}}/{{currentTask.totalCount}}）</text>
          </view>
          <view class="text-center cor-grey font12">
            <text v-if="currentTask.taskType == 4">{{ currentTask.completeCount || 0 }}人已完成</text>
            <text v-else>{{ currentTask.remarker }}</text>
          </view>
          <image :src="staticHost+'/coin_twins.png'" mode="widthFix" style="width:254rpx;margin:34rpx auto 34rpx;display:block;"></image>
          <view class="text-center">
            <text class="font-b" style="font-size:48rpx;margin-right:8rpx;">+{{ currentTask.golds }}</text>金币
            <text class="real-money" v-if="currentTask.golds">{{ formatMoney(currentTask.golds) }}元</text>
          </view>
          <button :class="['sub-btn', currentTask.cmped? 'finished':'']" @click="toDoTask">{{ currentTask.cmped ? '已完成' : '去完成' }}</button>
        </view>
      </view>

      <view class="red-bags">
        <view class="flex items-center">
          <view class="process-box" v-for="(item, index) in signGroupredbags" :key="index">
            <view class="process-bg-bar">
              <view class="process-bar" :style="{width: item.process + '%'}"></view>
            </view>

            <image :src="staticHost+'/process_point.png'"
              mode="widthFix"
              v-if="index==0"
              style="position:absolute;left:0;margin-left:-18rpx;"
              class="point-img"
            ></image>
            <view class="point-end">
              <image class="point-img" :src="staticHost+'/process_point.png'" mode="widthFix"></image>


              <image v-if="signIndex == 7 && item.bagIndex == 1" class="max-priza" :src="staticHost+'/max_priza.png'" mode="widthFix"></image>
              <block v-else>
                <view class="gold-r" :style="{width: item.golds>=1000 ? '124rpx': item.golds>=100 ? '106rpx': '96rpx'}">{{ item.golds }} 金币</view>
                <image v-if="item.received" class="red-bgs" :src="staticHost+'/redenvelope_cked.png'" mode="widthFix"></image>
                <image v-else class="red-bgs" :src="staticHost+'/redenvelope.png'" mode="widthFix"></image>
              </block>


              <view v-if="item.received && index==0" class="task-nums" style="width:100rpx;">签到成功</view>
              <view v-else-if="item.received" class="task-nums">{{item.cmpTask}}/{{item.totalTask}}</view>
              <view v-else-if="item.geted" class="red-rec-btn" @tap="showRecBagPop(item)">领红包</view>
              <view v-else class="task-nums">
                <text v-if="item.actived">{{item.cmpTask}}/</text>
                {{item.totalTask}}
              </view>
            </view>
          </view>
        </view>

        <view style="margin-top:76rpx;text-align:center;">
          每天领取1个签到红包后视为签到成功
        </view>
      </view>

      <view class="sign-tasks">
        <view class="flex justify-between">
          <text class="font16 font-semibold">签到进度</text>
          <text class="cor-grey" @tap="toMyTasks" v-if="signIndex>1">
            所有进度
            <image :src="staticHost+'/arrow_r_grey.png'" mode="widthFix" style="width:24rpx;margin-left:12rpx;"></image>
          </text>
        </view>

        <view v-if="!signTasks.length" class="cor-grey text-center font12" style="margin-top:90rpx;margin-bottom:90rpx;">今天还没有完成的任务，赶快去完成吧！</view>

        <view v-if="signTasks.length" class="task-box">
          <view v-for="(item, idx) in signTasks" :key="idx" class="task-item">
            <view class="left-cont">
              <view class="flex items-center;">
                <view class="font-black">
                  {{item.name}}
                  <text v-if="item.taskType == 3">（{{item.cmpCount}}/{{item.totalCount}}）</text>
                </view>
                <image :src="staticHost+'/coin.png'" mode="widthFix" style="width:38rpx;margin: 0 16rpx;"></image>
                <text class="gold-num font-semibold">+{{ item.golds}} 金币</text>
              </view>
              <view class="remarker">{{
                item.taskType == 4 ? `报名时间：${item.createTime}` : item.remarker
              }}</view>
            </view>

            <button v-if="item.taskType == 4"
              :class="['right-btn', (item.cmped || [100,101].includes(item.status)) ? 'finished': item.status == 1 ? 'is-approve' : '']"
              @click="clickRealTask(item)"
            >
              {{ item.cmped ? '已完成' : item.status == 1 ? '审核中':  item.status == 3 ? '不合格' : item.status == 100 ? '已过期' : item.status == 101 ? '已放弃': '去提交' }}
            </button>
            <button v-else :class="['right-btn', item.cmped ? 'finished':'']" @click="clickTask(item)">
              {{ item.cmped ? '已完成' : '去完成' }}
            </button>
          </view>
        </view>

      </view>

      <view style="width:100%;height:20rpx"></view>
    </scroll-view>

    <u-popup v-model="isVisibleRecSuccess"
      class="rec-bag-pop"
      :border-radius="12"
      mode="center"
      :mask="true"
      @close="hidePop"
    >
      <view :class="['relative', isMpKuaishou ? 'ks-rec-dia' : '']">
        <image :src="staticHost + '/rec_bag_success.png'" mode="widthFix"></image>
        <view class="flex items-center font18 font-medium justify-center absolute" style="top:94rpx;width:100%;">
          <image :src="staticHost +'/sign-seq.png'" mode="widthFix" style="width:32rpx;"></image>
          <text style="margin:0 32rpx;color:#660100;">红包领取成功</text>
          <image :src="staticHost +'/sign-seq.png'" mode="widthFix" style="width:32rpx;"></image>
        </view>
        <view class="absolute text-center" style="bottom:168rpx; width:100%;color:#C7372A;">
          <text style="font-size:64rpx;font-weight:600;margin-right:8rpx;">+{{ currentBag.golds }}</text>金币</view>
        <button class="pop-rec-btn" @tap="toWidthdraw">立即提现</button>
      </view>

    </u-popup>

    <WfCommonPop v-if="isViewFailedReason" v-model="isViewFailedReason" 
      :config="{title:'不合格原因', cancelBtnTxt:'取消', btnTxt: '重新提交', isConfirm: true}"
      @okEv="toSubjectDetail"
    >
      <view v-if="failedReason.examineText">{{failedReason.examineText}}</view>
      <scroll-view v-if="failedReason.examinePics.length" :scroll-y="true" class="scroll-imgs">
        <image v-for="(img, index) in failedReason.examinePics" :key="index" :src="img" mode="widthFix" style="width:100%;"></image>
      </scroll-view>
      
    </WfCommonPop>
  </view>
</template>

<script>
import { isMpAlipay, isMpBaidu, isMpToutiao, isMpKuaishou } from '@/utils/platform';
import statusBarInfo from '@/pages/welfare/mixins/statusBarInfo'
const app = getApp();
// import { encryptFn } from '@/utils/index'
// import { getRandomInt } from '@/utils/util'
import { SignNew, GetSignDetail, GoToCmp, ReceiveBag, GetRejectDetail } from '@/pages/welfare/api/index';
import { staticHost, version, appId } from '@/setting';
import WfCommonPop from '@/pages/welfare/components/WfCommonPop'


export default {
  mixins: [ statusBarInfo ],
  components: {
    WfCommonPop
  },
  computed: {
    isViewNextBtn() {
      // 如果是第一天
      let tasks = this.groupitemdetails;
      if (this.signIndex == 1) {
        // 是否是已完成
        if (!this.cmped || this.cg != 0) {
          return false;
        } else {
          if(tasks && tasks.length > 0){
            let curTask = tasks[0]
            if(curTask.taskType == 4 && curTask.status == 0){
              return false;
            }
          }
          return true;
        }
      } else {
        let curTask ={}
        if(tasks && tasks.length > 0){
          curTask = tasks[0]
        }
        if(curTask.id && curTask.status != 0 || !curTask.id){
          return true;
        }
        // 返回任务
        return false;
      }
    },
    currentTask() {
      let signGroupitem = this.signGroupitem;
      let jobTasks = this.groupitemdetails || [];
      let realTasks = this.taskListItems || [];
      let curIdx = this.currentTaskIndex;
      // 如果是第一天
      let { cmped, signIndex } = signGroupitem;
      if (signIndex == 1) {
        if (jobTasks.length) { 
          // 兼职任务是否完成
          if (!cmped) {
            // 未签到成功
            return jobTasks[0];
          } else {
            return this.getCurTask(jobTasks, realTasks, curIdx)
          }
        }
      } else {
        return this.getCurTask(jobTasks, realTasks, curIdx)
      }
      return {};
    },
    signTasks() {
      return this.groupitemdetails.filter(per => per.id > -1)
    }
  },
  data() {
    return {
      isMpAlipay,
      isMpBaidu,
      isMpToutiao,
      isMpKuaishou,
      isViewFailedReason: false,
      isVisibleRecSuccess: false,
      isWhiteAppBar: false,
      failedReason: {
        examinePics: []
      },
      staticHost,
      cmped: 0,
      signIndex: -1,
      groupitemdetails: [],
      signGroupitem: {
        status: 1
      },
      signGroupredbags: [],
      taskListItems: [],
      signId: '',
      currentBag: {},
      menuBottom: isMpAlipay ? 16: 0,
      currentTaskIndex: 0,
      cg:-1,
    };
  },
  options: { styleIsolation: 'shared' },
  onLoad(options) {
    this.signId = options.signId;
    // this.showRecBagPop({
    //   bagIndex: 1,
    //   cmpTask: 3,
    //   geted: 0,
    //   golds: 200,
    //   id: -1,
    //   received: 1,
    //   totalTask: 3
    // })
  },
  onShow() {
    console.log('onshow >> this.signId >>',this.signId);
    this.getSignDetail()
  },
  methods: {
    toCoinDetails() {
      this.$navigateTo('/pages/welfare/coinDetails')
    },
    formatMoney(gold) {
      if (gold > 0) {
        return gold / 1000;
      }
      return 0;
    },
    getCurTask(jobTasks, realTasks, curIdx) {
      // 返回任务
      if(jobTasks && jobTasks.length > 0){
        let firtstTask = jobTasks[0]
        if(firtstTask.taskType == 4 && firtstTask.status == 0){
          // 未提交任务
          return firtstTask;
        }
      }
      let len = realTasks && realTasks.length; 
      if(len) {
        if (curIdx > len-1) {
          return realTasks[len-1]
        }
        return realTasks[curIdx];
      } else {
        return jobTasks[0] || {};
      }
    },
    getSignDetail() {
      GetSignDetail({
        signId: this.signId
      }).then(res => {
        if (res.code == 200) {
          let { groupitemdetails, signGroupitem, signGroupredbags, taskListItems = [], signIndex, cmped } = res.data;

          groupitemdetails.forEach(per => {
            if (per.taskType == 4 && per.createTime) {
              per.createTime = per.createTime.substr(0,16)
            }
          })

          this.groupitemdetails = groupitemdetails;
          this.signGroupitem = signGroupitem;
          this.cg = res.cg
          // signGroupredbags = [{
          //   cmpTask: 3,
          //   geted: 1,
          //   golds: 60,
          //   id: -1,
          //   process: 100,
          //   received: 1,
          //   totalTask: 3
          // }, {
          //   cmpTask: 1,
          //   geted: 0,
          //   golds: 60,
          //   id: -1,
          //   process: 0,
          //   received: 0,
          //   totalTask: 6
          // }]

          for (let i = 0; i < signGroupredbags.length; i++) {
            const el = signGroupredbags[i];
            if (i == 0) {
              console.log('el.process >> ', el);
              el.process = (el.cmpTask / el.totalTask * 100).toFixed(2)
              console.log('el.process >> ', el.process);
              el.actived = true;
            } else {
              let prev = signGroupredbags[i-1];
              if (prev.cmpTask >= prev.totalTask) {
                el.actived = true;
                let startTask = el.cmpTask - prev.totalTask;
                let endTask = el.totalTask - prev.totalTask
                el.process = ((startTask / endTask) * 100).toFixed(2)
              }
            }
          }
          this.signGroupredbags = signGroupredbags

          taskListItems.forEach(row => {
            row.taskType = 4;
            row.name = row.title;
            row.golds = row.amount;
          });
          
          this.taskListItems = taskListItems;
          this.signIndex = signIndex;
          this.cmped = cmped;

          console.log('res> ', res);
        }
      })
    },
    toDoTask() {
      let taskType = this.currentTask.taskType;
      let signId = this.signId;
      if (taskType == 4) {
        let taskId = this.currentTask.taskId
        if(!taskId){
          taskId = this.currentTask.id
        }
        console.log("==currentTask=="+JSON.stringify(this.currentTask))
        this.$navigateTo(`/pages/welfare/taskDetail?taskId=${taskId}&submitId=${this.currentTask.subId}`)
      } else {
        GoToCmp({
          signId,
          taskType
        }).then(res => {
          if (res.code == 200 && res.data) {
            this.getSignDetail();
            let curTask = res.data;
            if (curTask.cmped) {
              // 是否领取红包
              let redBags = this.signGroupredbags;
              if (redBags.length) {
                if (redBags[0].geted && !redBags.received) {
                  this.$showToast('请领取红包')
                  return;
                }
              }
              this.$showToast('该任务已完成')
            } else {
              this.$navigateTo(`/pages/welfare/jobs?type=${taskType}&maxTimes=${curTask.totalCount}&detailId=${curTask.id}&signId=${signId}`)
            }
          }
        })
       }
    },
    showRecBagPop(item) {
      this.currentBag = item
      ReceiveBag({
        id: this.currentBag.id,
      }).then(res => {
        if (res.code == 200) {
          this.$showToast('领取成功')
          this.isVisibleRecSuccess = true;
          this.getSignDetail()

          let userInfo = app.globalData.userInfo;
          if (userInfo && userInfo.userId) {
            if (this.$uma && this.$uma.trackEvent) {
              this.$uma.trackEvent('receive_redbag', {
                userId: userInfo.userId,
                loginId: userInfo.loginId,
                appId,
                version
              });
            }
          }
        }
      })
    },
    toWidthdraw() {
      this.isVisibleRecSuccess = false;
      this.$navigateTo('/pages/welfare/withdrawal')
    },
    toMyTasks() {
      this.$navigateTo(`/pages/welfare/myTasks`)
    },
    clickRealTask(item) {
      if (item.status == 3) {
        this.failedReason = {
          examinePics: []
        }
        this.isViewFailedReason = true;
        this.fetchFailReason(item)
      } else {
        this.$navigateTo(`/pages/welfare/taskDetail?taskId=${item.taskId}&submitId=${item.subId}`)
      }
    },
    toSubjectDetail() {
      let {taskId, submitId} = this.failedReason
      this.$navigateTo(`/pages/welfare/taskDetail?taskId=${taskId}&submitId=${submitId}`)
    },
    clickTask(item) {
      let { taskType, cmped, totalCount, id } = item;
      if (cmped) {
        this.$showToast('该任务已完成')
      } else {
        if ([1,2,3].includes(Number(taskType))) {
          this.$navigateTo(`/pages/welfare/jobs?type=${taskType}&maxTimes=${totalCount}&detailId=${id}&signId=${this.signId}`)
        }
      }
    },
    fetchFailReason(item) {
      GetRejectDetail({
        id: item.subId
      }).then(res => {
        if (res.code == 200) {
          res.data.taskId = item.taskId;
          res.data.examinePics
          if (res.data.examinePics) {
            res.data.examinePics = res.data.examinePics.split(',')
          } else {
            res.data.examinePics = [];
          }
          this.failedReason = res.data;
        }
      })
    },
    scrollEv(e) {
      // console.log('scrollEv', e);
      let scrollTop =  e.target.scrollTop
      if (typeof scrollTop === 'number') {
        if (scrollTop > 50) {
          // tabbar背景切换
          this.isWhiteAppBar = true;
        } else {
          this.isWhiteAppBar = false;
        }
      }
    },
    toFollowList() {
      this.checkLogin(() => {
        this.$navigateTo('/pages/mine/followList');
      })
    },
    toLoginPg() {
      this.$navigateTo(`/pages/login/sms`)
    },
    checkLogin(callback) {
      if (!app.globalData.token) {
        this.toLoginPg()
      } else {
        callback && callback();
      }
    },
    hidePop() {

    },
    changTask(){
      let currentTaskIndex = this.currentTaskIndex;
      if(this.taskListItems && this.taskListItems.length > 0){
        if(currentTaskIndex >= this.taskListItems.length -1){
          currentTaskIndex = 0
        } else {
          currentTaskIndex++;
        }
        this.currentTaskIndex = currentTaskIndex
      }
    }
  },
};
</script>
<style lang="scss" scoped>  

  .index-page {
    width: 100%;
    background-color: #fff;
    overflow: hidden;
    height: 100vh;

    .box-1 {
      position: relative;
      margin-bottom: 16rpx;
      background: linear-gradient(180deg,#f50,#F9EEE7);
      height: 100vh;

      .ic-box-money {
        position: absolute;
        top: 0;
        right: 0;
        width: 320rpx;
      }

      .sign-center {
        background: #fff;
        margin: 0 32rpx;
        padding: 32rpx;
        border-radius: 32rpx;
        text-align: left;
        margin-top: 40rpx;

        .real-money {
          height: 72rpx;
          line-height: 72rpx;
          margin-left: 12rpx;
          padding: 0 16rpx;
          font-size: 38rpx;
          font-weight: 500;
          background: #FDE3E3;
          color:#F65352;
          border-radius: 28rpx 28rpx 28rpx 0rpx;
          margin-bottom: 6rpx;
        }

        .sub-btn {
          width: 240rpx;
          height: 64rpx;
          line-height: 64rpx;
          border-radius: 40rpx;
          background: #F65352;
          font-weight: 500;
          font-size: 28rpx;
          color: #fff;
          margin: 50rpx auto 0;
          text-align: center;

          &.finished {
            background: #CCCCCC;
          }
        }
      }
    }

    .red-bags {
      background: #fff;
      margin: 32rpx;
      border-radius: 32rpx;
      padding: 110rpx 52rpx 32rpx;

      .process-box {
        flex: 1;
        position: relative;
        width: 100%;
        height: 18rpx;
        border: 2rpx solid #DBDBDB;
        display: flex;
        align-items: center;

        .process-bg-bar {
          height: 10rpx;
          width: 100%;
          background: #DBDBDB;

          .process-bar {
            height: 100%;
            width: 0;
            border-radius: 20rpx;
            background: #f50;
          }
        }

        .point-img {
          width: 36rpx;
          display: block;
        }
        .point-end {
          position: absolute;
          right: 0;
          margin-right: -18rpx;
          z-index: 2;

          .max-priza {
            position: absolute;
            top: -60rpx;
            width: 116rpx;
            margin-left: 50%;
            transform: translateX(-50%);
            font-size: 12px;
          }

          .gold-r {
            position: absolute;
            top: -86rpx;
            width: 80rpx;
            margin-left: 50%;
            transform: translateX(-48%);
            font-size: 12px;
          }
          .red-bgs {
            width: 28rpx;
            position: absolute;
            top: -46rpx;
            left: 6rpx;
          }
          .red-rec-btn {
            position: absolute;
            top: 38rpx;
            left: 0;
            margin-left: 50%;
            transform: translateX(-50%);
            width: 104rpx;
            height: 40rpx;
            line-height: 40rpx;
            text-align: center;
            border-radius: 20px;
            font-size: 24rpx;
            color: #fff;
            background: #F65352;
          }
          .task-nums {
            position: absolute;
            width: 76rpx;
            margin-left: 50%;
            transform: translateX(-50%);
            line-height: 24rpx;
            text-align: center;
            top: 40rpx;
            font-size: 24rpx;
            line-height: 24rpx;
          }
        }
      }
    }

    .sign-tasks {
      background: #fff;
      margin: 32rpx;
      padding: 32rpx;
      border-radius: 32rpx;

      .task-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 48rpx 0 ;
        border-bottom: 1px solid #EAEBEF;

        .left-cont {
          overflow:hidden;
          margin-right:20rpx;

          .gold-num {
            color:#F96A35;
          }
          .remarker {
            margin-top: 8rpx;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            color: $grey_color;
          }
        }

        .right-btn {
          width: 144rpx;
          height: 64rpx;
          line-height: 64rpx;
          border-radius: 60rpx;
          background: #F65352;
          font-size: 28rpx;
          color: #fff;
          padding: 0;
          margin: 0;

          &.finished {
            background: #CCCCCC;
          }
          &.is-approve {
            color: #F96A35;
            background: #FEE7DE;
          }
        }
      }

    }
  }
  .scroll-imgs {
    max-height:64vh;
  }
</style>
